import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class TestValim extends JPanel implements ActionListener {
	ArrayList <Inimene> uldkogum = new ArrayList<Inimene>();
	ArrayList <Inimene> uldkogum_koopia = new ArrayList<Inimene>();
	ArrayList <Inimene> valim = new ArrayList<Inimene>();
	Timer timer;
	Ylesannete_kogu ylesannete_kogu, seletused;
	ValimiNumbrid valimi_numbrid;
	JScrollPane scrollPane, kerimisriba_all;
	JPanel nuppude_paneel, nuppude_paneel_3;
	JButton zuum_sisse_nupp, zuum_valja_nupp, uus_uldkogum_nupp, uus_valim_nupp, kustuta_v_nupp, eelmine_samm, jargmine_samm, vaata_lahendust, animeeri;
	JLabel valimite_arv, kesk_usalduspiirid, uld_k_suurus_lbl, valim_suurus_lbl, usaldusnivoo_lbl;
	JTextArea uldkogum_text, valim_text, usaldusnivoo_text;
	JMenuBar menubar;
    JMenu  simu_Menu, valimMenu, tooleht6_Menu, misMenu;
    JMenuItem item;
    ArrayList<JCheckBoxMenuItem> cbMenuItem = new ArrayList<JCheckBoxMenuItem>();
    NumberFormat nf = new DecimalFormat("#00.000");
    NumberFormat nf2 = new DecimalFormat("#0.0");
    boolean uldkogum_olemas = false;
	int zoomSize = 40, mitmes_valim = 0, display_mode = 0, slowtime=1;
	double uldkogumi_suurus=1000, valimi_suurus=30, lambikas, keskmine=180, maksimum_halve=30, summa=0, 
		valim_kesk=0, uld_kesk=0, al_kesk_usalduspiir, yl_kesk_usalduspiir, valimi_disp, valimi_halve, usaldusnivoo;
	double[][] student = { 
			{0.00, 0.8, 0.900, 0.950, 0.975, 0.990, 0.995, 0.9975, 0.999},
			{1.0, 1.376, 3.078, 6.314, 12.71, 31.82, 63.66, 127.3, 318,3}, 
			{2.0, 1.061, 1.886, 2.920, 4.303, 6.965, 9.925, 14.09, 22.33},
			{3.0, 0.978, 1.638, 2.353, 3.182, 4.541, 5.841, 7.453, 10.22},
			{4.0, 0.941, 1.533, 2.132, 2.776, 3.747, 4.604, 5.598, 7.173},
			{5.0, 0.920, 1.476, 2.015, 2.571, 3.365, 4.032, 4.773, 5.893},
			{6.0, 0.906, 1.440, 1.943, 2.447, 3.143, 3.707, 4.317, 5.208},
			{7.0, 0.896, 1.415, 1.895, 2.365, 2.998, 3.499, 4.029, 4.785},
			{8.0, 0.889, 1.397, 1.859, 2.306, 2.896, 3.355, 3.832, 4.501},
			{9.0, 0.883, 1.383, 1.833, 2.262, 2.821, 3.250, 3.690, 4.297},
			{10., 0.879, 1.372, 1.812, 2.228, 2.764, 3.169, 3.581, 4.144},
			{11., 0.876, 1.363, 1.796, 2.201, 2.718, 3.106, 3.497, 4.025},
			{12., 0.873, 1.356, 1.782, 2.179, 2.681, 3.054, 3.428, 3.930},
			{13., 0.870, 1.350, 1.771, 2.160, 2.650, 3.012, 3.372, 3.852},
			{14., 0.868, 1.345, 1.761, 2.145, 2.624, 2.977, 3.326, 3.787},
			{15., 0.866, 1.341, 1.753, 2.131, 2.602, 2.947, 3.286, 3.733},
			{16., 0.865, 1.337, 1.746, 2.120, 2.583, 2.921, 3.252, 3.686},
			{17., 0.863, 1.333, 1.740, 2.110, 2.567, 2.898, 3.222, 3.646},
			{18., 0.862, 1.330, 1.734, 2.101, 2.552, 2.878, 3.197, 3.611},
			{19., 0.861, 1.328, 1.729, 2.093, 2.539, 2.861, 3.174, 3.579},
			{20., 0.860, 1.325, 1.725, 2.086, 2.528, 2.845, 3.153, 3.552},
			{21., 0.859, 1.323, 1.721, 2.080, 2.518, 2.831, 3.135, 3.527},
			{22., 0.858, 1.321, 1.717, 2.074, 2.508, 2.819, 3.119, 3.505},
			{23., 0.858, 1.319, 1.714, 2.069, 2.500, 2.807, 3.104, 3.485},
			{24., 0.857, 1.318, 1.711, 2.064, 2.492, 2.797, 3.090, 4.467},
			{25., 0.856, 1.136, 1.708, 2.060, 2.485, 2.787, 3.078, 3.450},
			{26., 0.856, 1.315, 1.706, 2.056, 2.479, 2.779, 3.067, 3.435},
			{27., 0.855, 1.314, 1.703, 2.052, 2.473, 2.771, 3.056, 3.421},
			{28., 0.855, 1.313, 1.701, 2.048, 2.467, 2.763, 3.047, 3.408},
			{29., 0.854, 1.311, 1.699, 2.045, 2.462, 2.756, 3.038, 3.396},
			{30., 0.854, 1.310, 1.697, 2.042, 2.457, 2.750, 3.030, 3.385},
			{32., 0.853, 1.309, 1.694, 2.037, 2.449, 2.738, 3.015, 3.365},
			{34., 0.853, 1.307, 1.691, 2.032, 2.441, 2.728, 3.002, 3.348},
			{36., 0.852, 1.305, 1.688, 2.028, 2.434, 2.719, 2.990, 3.333},
			{38., 0.852, 1.304, 1.686, 2.024, 2.429, 2.712, 2.980, 3.319},
			{40., 0.851, 1.303, 1.684, 2.021, 2.423, 2.704, 2.971, 3.307},
			{42., 0.851, 1.302, 1.682, 2.018, 2.418, 2.698, 2.963, 3.296},
			{44., 0.850, 1.301, 1.680, 2.015, 2.414, 2.692, 2.955, 3.286},
			{46., 0.850, 1.300, 1.679, 2.013, 2.410, 2.687, 2.949, 3.277},
			{48., 0.849, 1.299, 1.677, 2.011, 2.407, 2.682, 2.948, 3.269},
			{50., 0.849, 1.298, 1.676, 2.009, 2.403, 2.678, 2.937, 3.261},
			{55., 0.848, 1.297, 1.673, 2.004, 2.396, 2.668, 2.925, 3.258},
			{60., 0.848, 1.296, 1.671, 2.000, 2.390, 2.660, 2.915, 3.232},
			{65., 0.847, 1.295, 1.669, 1.997, 2.385, 2.654, 2.906, 3.220},
			{70., 0.847, 1.294, 1.667, 1.994, 2.381, 2.648, 2.899, 3.211},
			{80., 0.846, 1.292, 1.664, 1.990, 2.374, 2.639, 2.887, 3.195},
			{90., 0.845, 1.291, 1.662, 1.987, 2.368, 2.632, 2.878, 3.183},
			{100, 0.845, 1.290, 1.660, 1.984, 2.365, 2.626, 2.871, 3.174},
			{120, 0.844, 1.289, 1.658, 1.980, 2.358, 2.617, 2.860, 3.159},
			{150, 0.844, 1.287, 1.655, 1.976, 2.351, 2.609, 2.849, 3.145},
			{200, 0.843, 1.286, 1.653, 1.972, 2.345, 2.601, 2.838, 3.131},
			{250, 0.843, 1.285, 1.651, 1.969, 2.341, 2.596, 2.832, 3.123},
			{300, 0.842, 1.284, 1.650, 1.968, 2.339, 2.592, 2.828, 3.118},
			{400, 0.842, 1.284, 1.649, 1.966, 2.336, 2.588, 2.823, 3.111},
			{500, 0.842, 1.283, 1.648, 1.965, 2.334, 2.586, 2.819, 3.107}
		};

	public TestValim() {
		ylesannete_kogu = new Ylesannete_kogu(1);
		seletused = new Ylesannete_kogu(0);
		
		this.setLayout(new BorderLayout());
		this.add(getMenuBar(), BorderLayout.NORTH);
		valimi_numbrid = new ValimiNumbrid();
		SimuPanel simupaneel = new SimuPanel();
		scrollPane = new JScrollPane(simupaneel);
		this.add(scrollPane, BorderLayout.CENTER);
		nuppude_paneel = new JPanel();
		uld_k_suurus_lbl = new JLabel("Üldkogumi suurus: ");
		valim_suurus_lbl = new JLabel("Valimi suurus: ");
		usaldusnivoo_lbl = new JLabel("Usaldusnivoo: ");
		tee_nupud_ja_labelid();
		lisa_nupud_ja_labelid();
		nupudlabelid_nahtamatuks();
		nupudlabelid_nahtavaks();
		kerimisriba_all = new JScrollPane(nuppude_paneel);
		this.add(kerimisriba_all, BorderLayout.SOUTH);
		
		timer = new Timer(40, new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				slowtime += 1;
				if (slowtime > 100) timer.stop();
				repaint();
			}
		});
	}
	
	private void tee_nupud_ja_labelid() {
		uldkogum_text = new JTextArea("" + (int) uldkogumi_suurus);
		uldkogum_text.setBorder(BorderFactory.createLineBorder(Color.black));
		uus_uldkogum_nupp = new JButton("Uus üldkogum");
		uus_uldkogum_nupp.addActionListener(this);
		valim_text = new JTextArea("" + (int) valimi_suurus);
		valim_text.setBorder(BorderFactory.createLineBorder(Color.black));
		uus_valim_nupp = new JButton("Uus valim");
		uus_valim_nupp.addActionListener(this);
		uus_valim_nupp.setEnabled(false);
		kustuta_v_nupp = new JButton("Kustuta valimid");
		kustuta_v_nupp.addActionListener(this);
		usaldusnivoo_text = new JTextArea("0.9");
		usaldusnivoo_text.setBorder(BorderFactory.createLineBorder(Color.black));
		eelmine_samm = new JButton("Eelmine samm");
		eelmine_samm.addActionListener(this);
		jargmine_samm = new JButton("Jargmine samm");
		jargmine_samm.addActionListener(this);
		vaata_lahendust = new JButton("Vaata lahendust");
		vaata_lahendust.addActionListener(this);
		animeeri = new JButton("Animeeri uuesti");
		animeeri.addActionListener(this);
	}

	public void lisa_nupud_ja_labelid() {
		nuppude_paneel.add(uld_k_suurus_lbl);
		nuppude_paneel.add(uldkogum_text);
		nuppude_paneel.add(uus_uldkogum_nupp);
		nuppude_paneel.add(valim_suurus_lbl);
		nuppude_paneel.add(valim_text);
		nuppude_paneel.add(uus_valim_nupp);
		nuppude_paneel.add(kustuta_v_nupp);
		nuppude_paneel.add(eelmine_samm);
		nuppude_paneel.add(jargmine_samm);
		nuppude_paneel.add(vaata_lahendust);
		nuppude_paneel.add(animeeri);
		repaint();
	}
	
	private void nupudlabelid_nahtamatuks() {
		uldkogum_text.setVisible(false);
		uus_uldkogum_nupp.setVisible(false);
		valim_text.setVisible(false);
		uld_k_suurus_lbl.setVisible(false);
		valim_suurus_lbl.setVisible(false);
		usaldusnivoo_lbl.setVisible(false);
		uus_valim_nupp.setVisible(false);
		kustuta_v_nupp.setVisible(false);
		usaldusnivoo_text.setVisible(false);
		eelmine_samm.setVisible(false);
		jargmine_samm.setVisible(false);
		vaata_lahendust.setVisible(false);
		animeeri.setVisible(false);
	}
	
	private void nupudlabelid_nahtavaks() {
		uldkogum_text.setVisible(true);
		uus_uldkogum_nupp.setVisible(true);
		valim_text.setVisible(true);
		uld_k_suurus_lbl.setVisible(true);
		valim_suurus_lbl.setVisible(true);
		usaldusnivoo_lbl.setVisible(true);
		uus_valim_nupp.setVisible(true);
		kustuta_v_nupp.setVisible(true);
		usaldusnivoo_text.setVisible(true);
	}
	
	private void ylesannete_nupud_nahtavaks() {
		eelmine_samm.setVisible(true);
		jargmine_samm.setVisible(true);
		vaata_lahendust.setVisible(true);
		kontrolli_ylesannete_nuppude_staatust();
	}
	
	public JMenuBar getMenuBar() {
		menubar = new JMenuBar();
		simu_Menu = new JMenu("Simulatsioon");
		valimMenu = new JMenu("Valimid");
		tooleht6_Menu = new JMenu("Tööleht 6");
		misMenu = new JMenu("Mis on mis");
		menubar.add(simu_Menu);
		menubar.add(valimMenu);
		menubar.add(tooleht6_Menu);
		menubar.add(misMenu);
		zuum_sisse_nupp = new JButton("Zoom +");
		zuum_sisse_nupp.addActionListener(this);
		menubar.add(zuum_sisse_nupp);
		zuum_valja_nupp = new JButton("Zoom -");
		zuum_valja_nupp.addActionListener(this);
		menubar.add(zuum_valja_nupp);
		valimite_arv = new JLabel ("Valimite arv : "+ (mitmes_valim));
		menubar.add(valimite_arv);
		
		item = new JMenuItem("Säti üldkogumeid");
		item.addActionListener(this);
		simu_Menu.add(item);
		item = new JMenuItem("Säti valimeid");
		item.addActionListener(this);
		simu_Menu.add(item);
		simu_Menu.add(item);
		for (int i = 0; i < ylesannete_kogu.ylesanded.size(); i++) {
			item = new JMenuItem("Ülesanne " + ylesannete_kogu.ylesanded.get(i).number);
			item.addActionListener(this);
			tooleht6_Menu.add(item);
		}
		item = new JMenuItem("Keskväärtus");
		item.addActionListener(this);
		misMenu.add(item);
		item = new JMenuItem("Dispersioon");
		item.addActionListener(this);
		misMenu.add(item);
		item = new JMenuItem("Standardhälve");
		item.addActionListener(this);
		misMenu.add(item);
		return menubar;
	}


	private void clear_valimid() {
		for (int i = 0; i < uldkogum.size(); i++) {
			uldkogum.get(i).valitud.clear();
		}
		// tühjendamise meetod valim_numbrid.clear();
		valimMenu.removeAll();
		cbMenuItem.clear();
		valimi_numbrid.clear_valim_nrd();
		mitmes_valim = 0;
		valimite_arv.setText("Valimite arv : " + this.mitmes_valim);
		// valim_kesk_text.setText("                                         ");
	}
	
	private void arvuta_kesk_usalduspiirid() {
		int r, v, k = (int) valimi_suurus - 1;
		double disp_summa=0, t, alfa;
		usaldusnivoo = Double.valueOf(usaldusnivoo_text.getText());
		alfa = (1 + usaldusnivoo) /2;
		for (r = 0; r < student.length; r++) {
			if(student[r][0] >= k) break;
		}
		for (v = 0; v < student[0].length; v++) {
			if(student[0][v] == alfa) break;
		}
		t = student[r][v];
		for (int i = 0; i < valimi_suurus; i++) {
			disp_summa += Math.pow(valim.get(i).pikkus - valim_kesk, 2);
		}
		valimi_disp = disp_summa / (valimi_suurus-1);
		valimi_halve = Math.sqrt(valimi_disp);
		al_kesk_usalduspiir = valim_kesk - (valimi_halve * t / Math.sqrt(valimi_suurus));
		yl_kesk_usalduspiir = valim_kesk + (valimi_halve * t / Math.sqrt(valimi_suurus));
	}

	private void add_uldkogum() {
		clear_valimid();
		if (uldkogum.size() > 0)
			uldkogum.clear();
		uldkogumi_suurus = Double.valueOf(uldkogum_text.getText());
		keskmine = 180; 
		maksimum_halve = 30;
		summa = 0;
		int mitu_korda_teha_randomit = 3; // hälve võib ka rohkem kui üks kord
		// minna läbi randomi, mis tähendab, et juhuslikud suurused satuvad soovitud keskmisele lähedamale tihedamalt

		for (int i = 0; i < uldkogumi_suurus; i++) {
			// �ldkogum
			Inimene uus = new Inimene(i);
			int j = (int) (Math.random() * 2);
			lambikas = maksimum_halve;
			for (int k = 0; k < mitu_korda_teha_randomit; k++) {
				lambikas = (Math.random() * lambikas);
			}
			if (j > 0) {
				uus.pikkus = keskmine + lambikas;
			} else {
				uus.pikkus = keskmine - lambikas;
			}
			// sugu
			uus.sugu = (int) (Math.random() * 2);
			
			uldkogum.add(uus);
			summa = summa + uus.pikkus;
		}
		uld_kesk = summa / uldkogumi_suurus;

		uldkogum_olemas = true;
		uus_valim_nupp.setEnabled(true);
		// valim_kesk_text.setText("                                         ");
		// yld_kesk_text.setText("" + nf.format(uld_kesk));
		uldkogum_text.setText("" + (int) uldkogumi_suurus);
		valimMenu.removeAll();
	}

	private void add_valim() {
		// Teame et statistikul ei õnnestu kunagi kogu üldkogumit täienisti mõõta, 
		// näiteks mõõta koolides ära kõik 10000 õpilast, seetõttu valib ta suvaliselt üle maa
		// näiteks 300 õpilast, et siis nende põhjal teha järeldused kõigi 10000 kohta
	
		uldkogum_koopia.clear();
		valim.clear();
		for (int i = 0; i < uldkogum.size(); i++) {
			uldkogum_koopia.add(uldkogum.get(i));
		}
		valimi_suurus = Double.valueOf(valim_text.getText());
		double summa = 0;

		for (int i = 0; i < valimi_suurus; i++) {
			double lambikas = (int) (Math.random() * uldkogum_koopia.size());
			Inimene valitud = uldkogum_koopia.get((int) lambikas);
			uldkogum_koopia.remove(valitud);
			valim.add(valitud);
			summa = summa + valitud.pikkus;
		}
		valim_kesk = summa / valimi_suurus;

		for (int i = 0; i < valim.size(); i++) {
			Inimene valitud = valim.get(i);
			for (int j = 0; j < uldkogum.size(); j++) {
				Inimene inimene = uldkogum.get(j);
				if (inimene.id_nr == valitud.id_nr) {
					inimene.valitud.add(new Integer(mitmes_valim));
				}
			}
		}

		valimite_arv.setText("Valimite arv : " + (this.mitmes_valim + 1));
		if (this.mitmes_valim > 25) {
			valimite_arv.setText("Valimite arv : " + this.mitmes_valim + " (Värvid otsas)");
		}
		
		valim_text.setText("" + (int) valimi_suurus);
		valimMenu.removeAll();
		cbMenuItem.clear();
		valimi_numbrid.addKesk(mitmes_valim,valim_kesk);
		valimi_numbrid.lisa_valim_nr(mitmes_valim);
		for (int i = 0; i <= mitmes_valim; i++) {
			cbMenuItem.add(new JCheckBoxMenuItem("Valim nr " + (i+1)));
			cbMenuItem.get(i).setSelected(valimi_numbrid.kas_id_olemas(i));
			valimMenu.add(cbMenuItem.get(i));
			cbMenuItem.get(i).addActionListener(this);
		}
		mitmes_valim++; 
	} // end ADD_VALIM

	/**
	 * Loob graafilise osa ja näitab seda.
	 */
	private static void createAndShowGUI() {
		// Loob akna ja määrab vaikimisi sulgemisoperatsiooni.
		JFrame frame = new JFrame("Simu");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Määrab akna sisu ja lisab selle aknale.
		TestValim testvalim = new TestValim();
		frame.setContentPane(testvalim);

		frame.setSize(931, 700); // Vaikimisi akna suurus algul 931x700.
		frame.setLocation(100, 100); // Akna kaugus ülevalt vasakult nurgast.
		frame.setVisible(true); // Teeb akna kasutajale nähtavaks.
	}

	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	} // end static void main

	public void zoom_in() {
		zoomSize = zoomSize + (int) Math.max(zoomSize * 0.5, 1);
		zuum_valja_nupp.setEnabled(true);
		if (zoomSize > 300) {
			zuum_sisse_nupp.setEnabled(false);
		}
	}

	public void zoom_out() {
		zoomSize = (int) (zoomSize * 0.7);
		zuum_sisse_nupp.setEnabled(true);
		if (zoomSize < 6) {
			zuum_valja_nupp.setEnabled(false);
		}
	}

	private void kontrolli_ylesannete_nuppude_staatust() {
		Ylesanne ylesanne = ylesannete_kogu.otsi_ylesanne_nr(ylesannete_kogu.getActive_ylesanne()); 
		
		eelmine_samm.setEnabled(true);
		jargmine_samm.setEnabled(true);
		vaata_lahendust.setEnabled(true);

		if (ylesanne.getActive_step_nr()==0) {
			eelmine_samm.setEnabled(false);
			vaata_lahendust.setEnabled(false);	
		}
		if (ylesanne.getActive_step_nr()==ylesanne.stepid.size()) {
			jargmine_samm.setEnabled(false);
		}
		
		if (ylesanne.getActive_step_nr() > 0) {
			Ylesande_step current_step = ylesanne.stepid.get(ylesanne.getActive_step_nr() - 1);
			if (current_step.isNaita_lahendust()) {
				vaata_lahendust.setEnabled(false);	
			}
		}
	}

	private void eelmine_samm() {
		Ylesanne ylesanne = ylesannete_kogu.otsi_ylesanne_nr(ylesannete_kogu.getActive_ylesanne()); 
		if (ylesanne.getActive_step_nr() > 0) {
				ylesanne.setActive_step_nr(ylesanne.getActive_step_nr() - 1);
		}
		kontrolli_ylesannete_nuppude_staatust();
	}

	private void jargmine_samm() {
		Ylesanne ylesanne = ylesannete_kogu.otsi_ylesanne_nr(ylesannete_kogu.getActive_ylesanne()); 
		
		if (ylesanne.getActive_step_nr() < ylesanne.stepid.size()) {
			ylesanne.setActive_step_nr(ylesanne.getActive_step_nr() + 1);
		}
		kontrolli_ylesannete_nuppude_staatust();
	}

	private void vaata_lahendust() {
		Ylesanne ylesanne = ylesannete_kogu.otsi_ylesanne_nr(ylesannete_kogu.getActive_ylesanne()); 
		if (ylesanne.getActive_step_nr() > 0) {
			Ylesande_step current_step = ylesanne.stepid.get(ylesanne.getActive_step_nr() - 1);
			current_step.setNaita_lahendust(true);
		}
		kontrolli_ylesannete_nuppude_staatust();
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		String command = evt.getActionCommand();
		if (command.equals("Säti üldkogumeid")) {
			nupudlabelid_nahtamatuks();
			nupudlabelid_nahtavaks();
			display_mode=0;
		}
		if (command.equals("Säti valimeid")) {
			nupudlabelid_nahtamatuks();
			nupudlabelid_nahtavaks();
			display_mode=0;
		}
		if (command.equals("Uus üldkogum")) {
			add_uldkogum();
		}
		if (command.equals("Uus valim")) {
			add_valim();
			arvuta_kesk_usalduspiirid();
		}
		if (command.equals("Kustuta valimid")) {
			clear_valimid();
		}	
		if (command.contains("Ülesanne ")) {
			nupudlabelid_nahtamatuks();
			command = command.substring(9, command.length());
			ylesannete_kogu.setActive_ylesanne(Integer.valueOf(command));
			Ylesanne ylesanne = ylesannete_kogu.otsi_ylesanne_nr(ylesannete_kogu.getActive_ylesanne());
			valimite_arv.setText("Valimite arv : " + ylesanne.getValimite_arv());
			display_mode=1;
			ylesannete_nupud_nahtavaks();
		}
		if (command.equals("Eelmine samm")) {
			eelmine_samm();
		}
		if (command.equals("Jargmine samm")) {
			jargmine_samm();
		}
		if (command.equals("Vaata lahendust")) {
			vaata_lahendust();
		}
		if (command.contains("Valim nr")) {
			for(int i=0; i < cbMenuItem.size(); i++) {
				if(cbMenuItem.get(i).isSelected() == false){
					valimi_numbrid.eemalda_valim_nr(i);
				} else {
					if(valimi_numbrid.kas_id_olemas(i) == false) valimi_numbrid.lisa_valim_nr(i);
				}
			}
		}
		if (command.equals("Keskväärtus")) {
			nupudlabelid_nahtamatuks();
			seletused.setActive_ylesanne(0);
			display_mode=2;
			animeeri.setVisible(true);
			slowtime=1; timer.start();
		}
		if (command.equals("Dispersioon")) {
			nupudlabelid_nahtamatuks();
			seletused.setActive_ylesanne(1);
			display_mode=2;
			animeeri.setVisible(true);
			slowtime=1; timer.start();
		}
		if (command.equals("Standardhälve")) {
			nupudlabelid_nahtamatuks();
			seletused.setActive_ylesanne(2);
			display_mode=2;
			animeeri.setVisible(true);
			slowtime=1; timer.start();
		}
		if (command.equals("Animeeri uuesti")) {
			slowtime = 1;
			timer.start();
		}
		if (command.equals("Zoom +")) {
			zoom_in();
		}
		if (command.equals("Zoom -")) {
			zoom_out();
		}
		super.repaint();
	}
	
	private class ValimiNumbrid {
		private ArrayList <Integer> valim_nrd = new ArrayList<Integer>();
		private ArrayList <ValimiKesk> keskvaartused = new ArrayList<ValimiKesk>();
		
		ValimiNumbrid() { }
		
		public void addKesk(int mitmesValim, double valimKesk) {
			ValimiKesk  kesk = new ValimiKesk( mitmesValim, valimKesk);
			keskvaartused.add(kesk);
		}
		
		public double returnKesk (int mitmesValim) {
			for(int j=0; j < keskvaartused.size(); j++) {
				if (keskvaartused.get(j).id == mitmesValim) {
					return keskvaartused.get(j).kesk;
				}
			}
			return 0;
		}
		private class ValimiKesk {
			int id;
			double kesk;
			ValimiKesk(int id, double kesk) {
				this.id=id;
				this.kesk=kesk;
			}
		}
		public boolean kas_id_olemas (int id) {
			for(int j=0; j < valim_nrd.size(); j++) {
					if (valim_nrd.get(j).intValue() == id) {
						return true;
					}
			}
			return false;
		}
		public void lisa_valim_nr (int id) {
			if(kas_id_olemas(id) == false) 
				valim_nrd.add(id);
		}
		public void eemalda_valim_nr (int id) {
			for(int j=0; j < valim_nrd.size(); j++) {
				if (valim_nrd.get(j).intValue() == id) {
					valim_nrd.remove(j);
				}
			}
		}
		public void clear_valim_nrd () { 
			valim_nrd.clear();
		}
		public ArrayList <Integer> getValim_numbrid() {
			return valim_nrd;
		}
	}

	private class Inimene {
		int id_nr;
		double pikkus;
		int sugu;
		ArrayList<Integer> valitud;
		Inimene(int id) {
			this.id_nr = id;
			valitud = new ArrayList<Integer>();
		}
	}

	private class SimuPanel extends JPanel implements ActionListener {

		SimuPanel() {
			this.setPreferredSize(new Dimension(20000,20000 ));
		}
		/*
		 * this paint method draws the simulation on the screen
		 */
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			
			switch (display_mode) {
				case 0:
					if (uldkogum_olemas) {
						display_uldkogum (g);
					} // end if (uldkogum_olemas)
					break;
				case 1:
					display_ylesanne(g, 1);
					break;
				case 2:	
					display_ylesanne(g, 2);
					break;
				default:
					System.out.println("Undefined display mode");
			}
		} // end paintComponent
		
		public void display_ylesanne(Graphics g, int mode) {
			int strHeight; //height of the string.
			Color display;
			String display_string;
			Ylesanne ylesanne = new Ylesanne(0);
			if(mode==1)	ylesanne = ylesannete_kogu.otsi_ylesanne_nr(ylesannete_kogu.getActive_ylesanne());
			if (mode==2) ylesanne = seletused.otsi_ylesanne_nr(seletused.getActive_ylesanne());
			ArrayList <String> stringid  = new ArrayList <String> ();	
			Font bigBoldFont = new Font("Arial Unicode MS", Font.BOLD, zoomSize/2);
			g.setFont(bigBoldFont);
			FontMetrics fm = g.getFontMetrics(bigBoldFont);
			strHeight = fm.getAscent();
			display = Color.black;
			g.setColor(display);
			display_string = ylesanne.getTekst();
			int reacounter = 0;
			stringid= poolita_string(g, display_string, bigBoldFont);
			for (int i = 0; i < stringid.size();i++) {
				g.drawString(stringid.get(i), 10, strHeight +  strHeight * reacounter++);
			}
			for (int i = 1; i < ylesanne.getActive_step_nr() + 1; i++) {
				Ylesande_step current_step = ylesanne.stepid.get(i-1);
				display_string = current_step.getVihje();
				display = new Color(0, 99, 0); // DarkSeaGreen;
				g.setColor(display);
				
				stringid= poolita_string(g, display_string, bigBoldFont);
				for (int z = 0; z < stringid.size();z++) {
					g.drawString(stringid.get(z), 30, strHeight +  strHeight * reacounter++);
				}
				if (current_step.isNaita_lahendust()) {
					display = new Color(65, 105, 225);
					g.setColor(display);
					display_string =current_step.getStepi_lahendus();	
					stringid= poolita_string(g, display_string, bigBoldFont);
					for (int z = 0; z < stringid.size();z++) {
						g.drawString(stringid.get(z), 30, strHeight +  strHeight * reacounter++);
					}
				}
			}
			
			if(mode == 2) {
				int eelmine_y =strHeight +  strHeight * reacounter;
				if (seletused.getActive_ylesanne() == 1) {
					g.setColor(Color.blue);
					g.drawString("Näide. Kui EX = 1/3 (8 + 13 + 9) = 10", 30,  strHeight + eelmine_y);
					g.drawString("siis DX = 1/2 [ (    -     )^2  +  (     -     )^2  +  (    -     )^2 ] ",30,strHeight*5 + eelmine_y);
					int parajasti_y = arvuta_kordinaat(strHeight + eelmine_y, strHeight*5 + eelmine_y);	
					int parajasti_seitsme_x = arvuta_kordinaat(30 + fm.stringWidth("Näide. Kui EX = 1/3 ( "), 30 + fm.stringWidth("siis DX = 1/2 [ ( "));
					int parajasti_13_x = arvuta_kordinaat(fm.stringWidth("Näide. Kui EX = 1/3 (8 + 13"),30 + fm.stringWidth("siis DX = 1/2 [ (    -     )^2  +  ("));
					int parajasti_10_x = arvuta_kordinaat(fm.stringWidth("Näide. Kui EX = 1/3 (8 +  13 + 9"),30 + fm.stringWidth("siis DX = 1/2 [ (    -     )^2  +  (     -     )^2  +  ("));
					int parajasti_10k1_x = arvuta_kordinaat(fm.stringWidth("Näide. Kui EX = 1/3 (8 + 13 + 9) = 10"),30 + fm.stringWidth("siis DX = 1/2 [ (    - "));
					int parajasti_10k2_x = arvuta_kordinaat(fm.stringWidth("Näide. Kui EX = 1/3 (8 + 13 + 9) = 10"),30 + fm.stringWidth("siis DX = 1/2 [ (    -     )^2  +  (     - "));
					int parajasti_10k3_x = arvuta_kordinaat(fm.stringWidth("Näide. Kui EX = 1/3 (8 + 13 + 9) = 10"),30 + fm.stringWidth("siis DX = 1/2 [ (    -     )^2  +  (     -     )^2  +  (    - "));
					g.setColor(new Color(0,180,0));
					g.drawString("8", parajasti_seitsme_x , parajasti_y );
					g.drawString("13", parajasti_13_x, parajasti_y);
					g.drawString("9", parajasti_10_x, parajasti_y);
					g.setColor(new Color(180,0,0));
					g.drawString("10", parajasti_10k1_x, parajasti_y);
					g.drawString("10", parajasti_10k2_x, parajasti_y);
					g.drawString("10", parajasti_10k3_x, parajasti_y);
				}
			}

		} // end display_ylesanne()
		
		public int arvuta_kordinaat( int algus , int lypp) {
			double teepikkus = lypp -  algus;
			teepikkus = teepikkus / (100) * slowtime;
			return (int) (algus + teepikkus);
		}

		public ArrayList <String> poolita_string(Graphics g, String display_string, Font bigBoldFont) {
			int strWidth;
			FontMetrics fm = g.getFontMetrics(bigBoldFont);
			strWidth = fm.stringWidth(display_string); 
			ArrayList <String> stringid  = new ArrayList <String> ();	
			if (strWidth > scrollPane.getViewport().getWidth()) { 				
				   // on vaja poolitada
				while (fm.stringWidth(display_string)>(scrollPane.getViewport().getWidth()-scrollPane.getViewport().getWidth()/10)) {
					strWidth = fm.stringWidth(display_string);
					int char_arv = display_string.length();
					int yhe_tahe_suurus=strWidth / char_arv;
					int fromIndex = (int) (scrollPane.getViewport().getWidth()-scrollPane.getViewport().getWidth()/4.2)/ yhe_tahe_suurus; 
					int poolita_kohal = display_string.indexOf(" ", fromIndex);
					if (poolita_kohal < 0) {
						break;
					}
					stringid.add(display_string.substring(0, poolita_kohal));
					display_string = display_string.substring(poolita_kohal, char_arv);
				}
			}
			stringid.add(display_string);
			return stringid;
		}

		public void display_uldkogum (Graphics g) {			
			g.setColor(Color.RED);
			int x_arv = ((int) Math.sqrt(uldkogum.size())) + 1;
			Font bigBoldFont = new Font("SansSerif", Font.BOLD, zoomSize/3);
			g.setFont(bigBoldFont);
			FontMetrics fm = g.getFontMetrics(g.getFont());
			int strHeight = fm.getAscent();
			ArrayList <Integer> valimid = valimi_numbrid.getValim_numbrid();
			int totalWidth = 0;
			int valim_y_algab = strHeight;
			
			for (int i = -1; i < valimid.size(); i++) {
				Color uusCol = Color.BLACK;
				String display_string = "";
				if (i >= 0) {
					uusCol = tagasta_varv(valimid.get(i).intValue());
				}
				g.setColor(Color.BLACK);
				if (i >= 0) {
					display_string = "| Valim nr ";
				} else {
					display_string = "Üldkogumi ";
				}
				int strWidth = fm.stringWidth(display_string); 
				g.drawString(display_string, 30 + totalWidth , valim_y_algab);
				totalWidth = totalWidth + (int)(strWidth);
				if (i >= 0) {	
				g.setColor(uusCol);
					display_string = "" + (valimid.get(i).intValue() + 1);
					g.drawString(display_string, 30 + totalWidth , valim_y_algab);
					strWidth = fm.stringWidth(display_string); 
					
				}	else {
					strWidth = fm.stringWidth(" "); 
				}
				totalWidth = totalWidth + (int)(strWidth * 2) ;
				
					display_string = "Keskväärtus: ";
					g.setColor(Color.BLACK);
					g.drawString(display_string, 30 + totalWidth ,valim_y_algab);
					strWidth = fm.stringWidth(display_string); 
					totalWidth = totalWidth + (int)(strWidth) ;
					if (i >= 0) {	
					display_string = "" + nf2.format(valimi_numbrid.returnKesk(valimid.get(i).intValue()));
					g.setColor(uusCol);
					} else {
						display_string = "" + nf2.format(uld_kesk);
					}
					g.drawString(display_string, 30 + totalWidth , valim_y_algab);
					strWidth = fm.stringWidth(display_string); 
					totalWidth = totalWidth + (int)(strWidth * 1.4) ;
					/*
					g.setColor(Color.BLACK);	
					g.drawString(" Keskväärtus:", 36 + i*150, 15);
					g.setColor(uusCol);	
					g.drawString("" + valimi_numbrid.returnKesk(valimid.get(i).intValue()), 30 + i*150, 15);
					*/
			}

			int counter = 1;
			for (int i = 1; i < x_arv; i++) {
				for (int j = 1; j < x_arv * 1.6; j++) {
					ArrayList<Integer> display = new ArrayList<Integer> ();
					// moment vytame randomiga kas mees naine
					//enam ei tohi see display =, vaid tuleb käsitsi ehitada
					for (int p = 0; p < uldkogum.get(counter - 1).valitud.size(); p++)  {
						if (valimi_numbrid.kas_id_olemas(uldkogum.get(counter - 1).valitud.get(p).intValue()))	
							display.add(uldkogum.get(counter - 1).valitud.get(p));
					}
					drawMan(g, 30 + (int) ((j - 1) * zoomSize * 1.44444),
							valim_y_algab  * 4 + (i - 1) * zoomSize * 2, zoomSize, display,
							uldkogum.get(counter - 1).pikkus, counter,
							uldkogum.get(counter - 1).sugu);
					counter++;
					if (counter > uldkogum.size()) {
						break;
					}
				} // end for j
				if (counter > uldkogum.size()) {
					break;
				}
			} // end for i
		}
		public Color tagasta_varv (int valimi_nr) {		
			Color display = Color.GREEN;
			if (valimi_nr == 0)
				display = new Color(189, 183, 107); // DarkKhaki
			if (valimi_nr == 1)
				display = new Color(255, 140, 0); // DarkOrange
			if (valimi_nr == 2)
				display = new Color(205, 92, 92); // IndianRed
			if (valimi_nr == 3)
				display = new Color(0, 255, 0); // Green
			if (valimi_nr == 4)
				display = new Color(255, 105, 180); // HotPink
			if (valimi_nr == 5)
				display = new Color(255, 20, 147); // DeepPink
			if (valimi_nr == 6)
				display = new Color(255, 127, 80); // Coral
			if (valimi_nr == 7)
				display = new Color(218, 165, 32); // Goldenrod
			if (valimi_nr == 8)
				display = new Color(255, 69, 0); // OrangeRed
			if (valimi_nr == 9)
				display = new Color(250, 128, 114); // Salmon
			if (valimi_nr == 10)
				display = new Color(255, 215, 0); // Gold
			if (valimi_nr == 11)
				display = new Color(255, 0, 0); // Red
			if (valimi_nr == 12)
				display = new Color(240, 230, 140); // Khaki
			if (valimi_nr == 13)
				display = new Color(230, 230, 250); // Lavender
			if (valimi_nr == 14)
				display = new Color(238, 130, 238); // Violet
			if (valimi_nr == 15)
				display = new Color(153, 102, 204); // Amethyst
			if (valimi_nr == 16)
				display = new Color(106, 90, 205); // SlateBlue
			if (valimi_nr == 17)
				display = new Color(152, 251, 152); // PaleGreen
			if (valimi_nr == 18)
				display = new Color(154, 205, 50); // YellowGreen
			if (valimi_nr == 19)
				display = new Color(143, 188, 143); // DarkSeaGreen
			if (valimi_nr == 20)
				display = new Color(192, 192, 192); // Silver
			if (valimi_nr == 21)
				display = new Color(210, 105, 30); // Chocolate
			if (valimi_nr == 22)
				display = new Color(160, 82, 45); // Sienna
			if (valimi_nr == 23)
				display = new Color(65, 105, 225); // RoyalBlue
			if (valimi_nr == 24)
				display = new Color(127, 255, 212); // Aquamarine
			return display;
		}
		
		public void drawMan(Graphics g, int x, int y, int size,
				ArrayList<Integer> col, double andmed, int mitmes, int gender) {
			Color display;
			if (col.size() > 0) {
				display = Color.GREEN;
				for (int k = 0; k < col.size(); k++) {
					Integer valimi_nr = col.get(k);
						display = tagasta_varv(valimi_nr);
						g.setColor(display);
						g.fillRect(x - size / 5, y - size / 5 + (int) (k * (size * 1.444)/ col.size()), size, (int) (size * 1.444) / col.size());
				}
			}
			g.setColor(Color.magenta);
			String temp = "" + mitmes;
			Font plainFont = new Font("Serif", Font.PLAIN, (int) (size / 3.5));
			g.setFont(plainFont);
			g.drawString(temp, x - size / 5, y - size / 4);
			g.setColor(Color.black);
			g.fillOval(x + (int) (0.25 * size), y + (int) (0.08 * size), size / 6, size / 6); // pea
			int xPoints[] = new int[] { 1 };
			int yPoints[] = new int[] { 1 };
			if (gender == 0) {
				xPoints = new int[] { x + (int) (2.5 * size / 12),
						x + (int) (5.5 * size / 12), x + (int) (4 * size / 12) };
				yPoints = new int[] { y + (int) (3 * size / 12),
						y + (int) (3 * size / 12), y + (int) (6 * size / 12) };
				g.fillPolygon(xPoints, yPoints, 3); // õlad

				xPoints = new int[] { x + (int) (5.5 * size / 12),
						x + (int) (7 * size / 12), x + (int) (7 * size / 12),
						x + (int) (6.5 * size / 12), x + (int) (6 * size / 12),
						x + (int) (5 * size / 12) };
				yPoints = new int[] { y + (int) (3 * size / 12),
						y + (int) (6 * size / 12), y + (int) (6.5 * size / 12),
						y + (int) (6.5 * size / 12), y + (int) (6 * size / 12),
						y + (int) (4 * size / 12) };
				g.fillPolygon(xPoints, yPoints, 6); // kasi

				xPoints = new int[] { x + (int) (2.5 * size / 12),
						x + (int) (1 * size / 12), x + (int) (1 * size / 12),
						x + (int) (1.5 * size / 12), x + (int) (2 * size / 12),
						x + (int) (3 * size / 12) };
				g.fillPolygon(xPoints, yPoints, 6); // kasi 2 (y sama)

				xPoints = new int[] { x + (int) (5 * size / 12),
						x + (int) (5 * size / 12), x + (int) (6.5 * size / 12),
						x + (int) (1.5 * size / 12), x + (int) (3 * size / 12),
						x + (int) (3 * size / 12) };
				yPoints = new int[] { y + (int) (4 * size / 12),
						y + (int) (4.5 * size / 12),
						y + (int) (8.5 * size / 12),
						y + (int) (8.5 * size / 12),
						y + (int) (4.5 * size / 12), y + (int) (4 * size / 12) };
				g.fillPolygon(xPoints, yPoints, 6); // kleit

				xPoints = new int[] { x + (int) (5.1 * size / 12),
						x + (int) (5.1 * size / 12), x + (int) (5 * size / 12),
						x + (int) (4.5 * size / 12),
						x + (int) (4.3 * size / 12),
						x + (int) (4.3 * size / 12) };
				yPoints = new int[] { y + (int) (8.5 * size / 12),
						y + (int) (11.8 * size / 12),
						y + (int) (12 * size / 12), y + (int) (12 * size / 12),
						y + (int) (11.8 * size / 12),
						y + (int) (8.5 * size / 12) };
				g.fillPolygon(xPoints, yPoints, 6); // jalg

				xPoints = new int[] { x + (int) (2.9 * size / 12),
						x + (int) (2.9 * size / 12), x + (int) (3 * size / 12),
						x + (int) (3.5 * size / 12),
						x + (int) (3.7 * size / 12),
						x + (int) (3.7 * size / 12) };
				g.fillPolygon(xPoints, yPoints, 6); // jalg
			}

			if (gender == 1) { // mees
				xPoints = new int[] { x + (int) (2.2 * size / 12), // parem ylg
						x + (int) (5.8 * size / 12), // vasak ylg
						x + (int) (5.9 * size / 12), // ylakumerus
						x + (int) (6.0 * size / 12),
						x + (int) (6.3 * size / 12), // kae aarmine tipp yleval
						x + (int) (6.3 * size / 12), // kae aarmine tipp all
						x + (int) (5.9 * size / 12),
						x + (int) (5.5 * size / 12),
						x + (int) (5.5 * size / 12),
						x + (int) (5.3 * size / 12), // kaenlaalune
						x + (int) (5.1 * size / 12),
						x + (int) (5.1 * size / 12),
						x + (int) (4.6 * size / 12),// jala tipp
						x + (int) (4.1 * size / 12),
						x + (int) (4.1 * size / 12),
						x + (int) (4.0 * size / 12), // hargivahe
						x + (int) (3.9 * size / 12),
						x + (int) (3.9 * size / 12),
						x + (int) (3.4 * size / 12),// jala tipp
						x + (int) (2.9 * size / 12),
						x + (int) (2.9 * size / 12),
						x + (int) (2.7 * size / 12), // kaenlaalune
						x + (int) (2.5 * size / 12),
						x + (int) (2.5 * size / 12),
						x + (int) (2.1 * size / 12),
						x + (int) (1.7 * size / 12), // kae aarmine tipp all
						x + (int) (1.7 * size / 12), // kae aarmine tipp yleval
						x + (int) (2.0 * size / 12),
						x + (int) (2.1 * size / 12) // ylakumerus
				};
				yPoints = new int[] { y + (int) (3 * size / 12), // parem ylg
						y + (int) (3 * size / 12), // vasak ylg
						y + (int) (3.2 * size / 12), // ylakumerus
						y + (int) (3.2 * size / 12),
						y + (int) (3.5 * size / 12), // kae aarmine tipp yleval
						y + (int) (7.2 * size / 12), // kae aarmine tipp all
						y + (int) (7.5 * size / 12),
						y + (int) (7.2 * size / 12),
						y + (int) (4 * size / 12), 
						y + (int) (3.8 * size / 12), // kaenlaalune
						y + (int) (4 * size / 12),
						y + (int) (11.8 * size / 12),
						y + (int) (12 * size / 12), // jala tipp
						y + (int) (11.8 * size / 12),
						y + (int) (7 * size / 12),
						y + (int) (6.8 * size / 12), // hargivahe
						y + (int) (7 * size / 12), 
						y + (int) (11.8 * size / 12),
						y + (int) (12 * size / 12),
						y + (int) (11.8 * size / 12),
						y + (int) (4 * size / 12),
						y + (int) (3.8 * size / 12), // kaenlaalune
						y + (int) (4 * size / 12), 
						y + (int) (7.2 * size / 12),
						y + (int) (7.5 * size / 12),
						y + (int) (7.2 * size / 12), // kae aarmine tipp all
						y + (int) (3.5 * size / 12), // kae aarmine tipp yleval
						y + (int) (3.2 * size / 12),
						y + (int) (3.2 * size / 12) // ylakumerus
				};
				g.fillPolygon(xPoints, yPoints, 29); // mees
			} // end if (gender == 1)
			g.setColor(Color.BLUE);
			temp = "" + ((int) andmed) + "cm";
			g.drawString(temp, x - size / 5, y + (int) (size * 1.2));
		}
		@Override
		public void actionPerformed(ActionEvent e) { }
	} // end class SimuPanel
}
